const Sequelize = require('sequelize');
const MySequelize = require('./db/dbConfg');
const User = require('./model/userModel');
const Blog = require('./model/blogModel');
// token
const { sign, verify } = require('jsonwebtoken');
const secret = 'zwjblog';
const jwt = require('koa-jwt')({ secret });

const { Op } = Sequelize;   


const Router = require("koa-router");
const router = new Router()
const Koa = require('koa');
// 1.先导入bodyParser
const bodyParser = require('koa-bodyparser');
const app = new Koa();
// 2.再使用bodyParser中间件(要在挂载路由前使用中间件bodyParser())
app.use(bodyParser())
// 3.再挂载路由(这一步要在使用bodyParser之后,否则无法获取请求体数据)
app.use(router.routes());

app.use(async ctx => {
    // the parsed body will store in ctx.request.body
    // if nothing was parsed, body will be an empty object {}
    ctx.body = ctx.request.body;
});
app.use(function (req, res, next) {
    //设置允许跨域的域名，*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin", "*");
    //允许的header类型
    res.header("Access-Control-Allow-Headers", "*");
    //跨域允许的请求方式
});


//校验token
async function checkToken(ctx, next) {
    let token = ctx.request.headers.authorization;
    console.log(token, "token")
    if (token) {
        try {
            const tokenItem = verify(token, secret)
            if (tokenItem) {
                const { time, timeout } = tokenItem
                let nowTime = new Date().getTime();
                if (nowTime - time <= timeout) {
                    // token有效未过期
                    await next()
                    console.log("token校验成功")
                } else {
                    ctx.body = {
                        mssage: "token已过期,请重新登录",
                        code: 401
                    }
                }
            }
        } catch (error) {
            ctx.body = {
                mssage: "token错误请重新登录",
                code: 401
            }
        }
    } else {
        ctx.body = {
            mssage: "请求头未携带token",
            code: 401
        }
    }

}

router.get('/', async (ctx, next) => {
    ctx.body = {
        mssage: "这是测试信息",
        code: 200,
        data: {
            dhr: "我是邓鸡蛋我怕谁",
            zwj: "zwj 666"
        }
    }
})
router.post('/register', bodyParser(), async (ctx, next) => {
    console.log(ctx.request.body)
    let rs = await User.findOne({
        where: { sname: ctx.request.body.sname },
    });
    if (rs) {
        ctx.body = {
            mssage: "用户名已存在",
            code: 500
        }
    } else {
        try {
            const user = await User.create(ctx.request.body);
            ctx.body = {
                msg: "注册成功!!!",
                code: 200,
                data: user

            }
        } catch (error) {
            console.log('error', error)
            if (error) {
                ctx.body = {
                    mssage: "注册失败",
                    code: 500,

                }

            }
        }
    }
})
router.post('/login', async (ctx, next) => {
    let userInfo = ctx.request.body;
    console.log("ctx", ctx.request.body)
    // 查询用户信息在数据表中是否存在
    let user = await User.findOne({
        where: { sname: userInfo.sname },
    });
    if (user || userInfo.sname) {
        const token = sign({ user, test: 'testok', time: new Date().getTime(), timeout: 1000 * 60 * 60 * 2 }, secret, { expiresIn: '2h' });
        ctx.body = {
            mssage: '登录成功',
            code: 200,
            token
        }
    } else {
        ctx.body = {
            mssage: '用户不存在',
            code: 400,
        }
    }
})
router.post('/userInfo', bodyParser(), async (ctx, next) => {
    // let userInfo = ctx.request.body;
    // ctx.request.header = {'authorization': "Bearer " + (params.token || '')}
    let token = ctx.request.header.authorization;
    console.log(token)
    let userInfo = verify(token, secret)
    ctx.body = {
        mssage: "获取用户信息成功",
        code: 200,
        data: userInfo
    }

})
// 退出登录
router.post('/logOut', bodyParser(), async (ctx, next) => {
    let token = ctx.request.header.authorization;
    console.log(token)
    let userInfo = verify(token, secret)
    if (userInfo) {
        ctx.body = {
            mssage: "退出成功",
            code: 200,
            token: null  //此时前端把这个token添加到请求头

        }
    }
})
router.post('/list', async (ctx, next) => {
    checkToken(ctx, next);
})
app.listen(3003, () => {
    console.log("server is running  localhost:3003")
})
router.post('/addBlog', bodyParser(), async (ctx, next) => {
    console.log(ctx.request.body)
    let rs = await Blog.findOne({
        where: { title: ctx.request.body.title },
    });
    if (rs) {
        ctx.body = {
            mssage: "文章标题重复",
            code: 400
        }
    } else {
        try {
            const blog = await Blog.create(ctx.request.body);
            ctx.body = {
                msg: "发布文章成功!",
                code: 200,
                data: blog

            }
        } catch (error) {
            console.log('error', error)
            if (error) {
                ctx.body = {
                    mssage: "发布文章失败",
                    code: 500,

                }

            }
        }
    }
})
// 获取博客内容
router.post('/getBlogList', bodyParser(), async (ctx, next) => {
    try {
        console.log("req", ctx.request.body)
        let res = await Blog.findAndCountAll({
            where: { title: { [Op.like]: `%${ctx.request.body.title}%` } },
        });
        let result = await Blog.findAll({
            where: { title: { [Op.like]: `%${ctx.request.body.title}%` } },
            limit: Number(ctx.request.body.pageSize),
            offset: (Number(ctx.request.body.pageNum) - 1) * Number(ctx.request.body.pageSize),
        })
        console.log("result", result)
        let total = res.count || 0
        let current = ctx.request.body.pageNum || 1;
        ctx.body = {
            msg: "获取文章列表成功!",
            code: 200,
            data: result,
            total,
            current
        }
    } catch (error) {
        ctx.body = {
            mssage: "获取文章列表失败",
            code: 500,
        }
    }

})
// 编辑博客内容
router.post('/updateBlog', bodyParser(), async (ctx, next) => {
    console.log(ctx.request.body)
    let title = ctx.request.body.title;
    let content = ctx.request.body.content;
    let result = await Blog.update({ title, content }, { where: { uuid: ctx.request.body.uuid } })
    ctx.body = {
        msg: "更新文章成功!",
        code: 200,
        data: result

    }
})
// 删除博客内容
router.post('/deleteBlog', bodyParser(), async (ctx, next) => {
    console.log(ctx.request.body)
    let uuid = ctx.request.body.uuid;
    let result = await Blog.destroy({ where: { uuid: uuid } })
    ctx.body = {
        msg: "删除文章成功!",
        code: 200,
        data: result

    }
})
module.exports = router









